<?php
/**
 * Created by PhpStorm.
 * User: wangsong
 * Time: 2018/5/30 17:05
 */

namespace App\Project\Image;

use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class ImageUpload
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var string
     */
    protected $key;

    /**
     * @var array
     */
    protected $files = [];

    /**
     * ImageUpload constructor.
     * @param \Illuminate\Http\Request $request
     * @param  string                  $key
     */
    public function __construct(Request $request, $key)
    {
        $this->request = $request;
        $this->key     = $key;
    }

    public function src()
    {
        $files = (array) $this->file();

        foreach ($files as $file) {

            $this->files[] = (new Path($file->store('public/images')))->src()->attribute();
        }

        return $this;
    }

    public function mergeTo(array &$array, $key)
    {

        //  src 合并到数组中
        if (array_key_exists($key, $array)) {
            $array[$key] = array_merge(array_values($array[$key]), $this->files);
        } else {
            $array[$key] = $this->files;
        }

        return $array;
    }

    public function file()
    {
        return $this->request->file($this->key);
    }
}